<?php
/**
 * icsshow: display remote ICS calendar events
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 */
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_icsshow extends DokuWiki_Syntax_Plugin {

    protected $_pattern = 'ics_show';

    /**
     * return some info
     */
    function getInfo(){
        return array(
            'author' => 'Stephane Chamberland',
            'email'  => 'dokuwiki@meteokid.ca',
            'date'   => '2009-02-21',
            'name'   => 'ICS show Plugin',
            'desc'   => 'Display remote ICS clendar events',
            'url'    => 'http://dokuwiki.org/plugin:icsshow',
        );
    }

    /**
     * What kind of syntax are we?
     */
    function getType(){
        return 'substition';
    }

    /**
     * What about paragraphs?
     */
    function getPType(){
        return 'block';
    }

    /**
     * Where to sort in?
     */
    function getSort(){
        return 154;
    }


    /**
     * Connect pattern to lexer
     */
    function connectTo($mode) {
        $this->Lexer->addSpecialPattern('<'.$this->_pattern.'>.*?</'.$this->_pattern.'>',$mode,'plugin_icsshow');
    }


    /**
     * Handle the match
     */
    function handle($match, $state, $pos, &$handler){
        global $ID;
        $len = strlen($this->_pattern) + 2;
        $match = substr($match,$len,-1*($len+1)); // remove form wrap

        $linelist = explode("\n",$match);
        $cals = array();
        $options = array();
        $idx=0;

        //msg('---',0);
        foreach($linelist as $line) {
            $line = trim($line);
            if(!$line || $line[0]=='#') continue;
            $args = $this->_parse_line($line);
            $args = explode(' ',$line,2);
            $args[0] = strtolower($args[0]);
            if($line[0]=='$') {
                $args[0] = substr($args[0],1);
                //if(!isset($this->argcheck[$args[0]])){
                //    msg(sprintf($this->getLang('e_unknowntype'),hsc($args[0])),-1);
                //    continue;
                //}
                //if(count($args) < $this->argcheck[$args[0]]){
                //    msg(sprint`12f($this->getLang('e_missingargs'),hsc($args[0]),hsc($args[1])),-1);
                //    continue;
                //}
                $options[$args[0]] = $args;
                //msg('ics option:'.$args[0].' : '.hsc($args[1]),0);
            } else {
                $name = trim($args[0]);
                $url = $name;
                if(count($args)==1) $name = $ID.$idx;
                else $url=trim($args[1]);
                $idx++;
                $cals[$name] = $url;
                //TODO: check that url is valid            
                //msg('ics cal:'.$name.' : '.$url,0);
            }
        }
        //echo '<pre>';
        //print_r($cals)."\n"; 
        //print_r($options)."\n"; 
        //echo '</pre>';
        return array('cals'=>$cals,'options'=>$options);
    }

    /**
     * Create output
     */
    function render($format, &$R, $data) {
        global $ID;
        if($format != 'xhtml') return false;
        $R->info['cache'] = false; // don't cache

        $ics =& plugin_load('helper', 'icsshow');
        if (is_null($ics) || plugin_isdisabled('icsshow')) return false;

        //if (!$this->configloaded){ 
        //    $this->loadConfig(); 
        //}
        
        //echo '<pre>';
        //print_r($data['cals'])."\n"; 
        //echo '</pre>';
        //echo '<pre>';        
        //print_r($data['options'])."\n"; 
        //echo '</pre>';
        //echo '<pre>';        
        //print_r($this->conf);
        //echo '</pre>';
        $R->doc .= $ics->_render_xhtml($data['cals'],$data['options']);

        return true;
    }

    /**
     * Parse a line into (quoted) arguments
     *
     * @author William Fletcher <wfletcher@applestone.co.za>
     */
    function _parse_line($line) {
        $args = array();
        $inQuote = false;
        $len = strlen($line);
        for(  $i = 0 ; $i <= $len; $i++ ) {
            if( $line{$i} == '"' ) {
                if($inQuote) {
                    array_push($args, $arg);
                    $inQuote = false;
                    $arg = '';
                    continue;
                } else {
                    $inQuote = true;
                    continue;
                }
            } else if ( $line{$i} == ' ' ) {
                if($inQuote) {
                    $arg .= ' ';
                    continue;
                } else {
                    if ( strlen($arg) < 1 ) continue;
                    array_push($args, $arg);
                    $arg = '';
                    continue;
                }
            }
            $arg .= $line{$i};
        }
        if ( strlen($arg) > 0 ) array_push($args, $arg);
        return $args;
    }


}

//Setup VIM: ex: et ts=4 enc=utf-8 :
